import store from "../store/index";
import queryParams from "../utils/queryParams";
import {
	HTTP_URL
} from "./http.api";
import md5Libs from "@/uview-ui/libs/function/md5";
let baseUrl = ''
// 不要直接使用这个请求
/**
 * option:timeout 超时提示  blob:返回的是二进制文件  baseUrl:基本域名
 * timeoutNum:超时时间
 */
function request(url, params = {}, data = {}, method = 'POST', option = {}) {
	let headerMethod = false
	if (data && data.headerMethod) {
		headerMethod = true
		delete data.headerMethod
	}
	return new Promise((resolve, reject) => {
		const URL_OBJ = HTTP_URL[url]
		let index = URL_OBJ.url.indexOf('tripapi')
		// let index = URL_OBJ.url.indexOf('XunfuPay')
		try {
			if (option.baseUrl) {
				baseUrl = option.baseUrl
			} else if (index !== -1) {
				baseUrl = 'https://tripapi.kailly.com'
			} else {
				// #ifdef H5
				baseUrl = process.env.NODE_ENV === 'production' ? store.state.vuex_businessObj.resquest : ""
				// #endif
				// #ifndef H5
				baseUrl = index !== -1 ? 'https://tripapi.kailly.com' : store.state.vuex_businessObj.resquest
				// #endif
			}
		} catch (e) {

		}
		if (option.requestPath) {
			url = baseUrl + option.requestPath
		} else {
			url = baseUrl + URL_OBJ.url
		}
		if (option.typetype == 22) {
			console.log('interceptorRequest(url, params)', interceptorRequest(url, params))
			reject()
			return
		}
		uni.request({
			url: option.requestPath ? url : interceptorRequest(url, params),
			method: method,
			data: data,
			timeout: option.timeoutNum || 15000,
			// 支付宝不支持responseType
			// #ifndef MP-ALIPAY  
			responseType: option.blob ? 'arraybuffer' : 'text',
			// #endif
			// #ifdef MP-ALIPAY
			dataType: option.blob ? 'arraybuffer' : 'json',
			// #endif
			header: {
				'content-type': headerMethod ? 'application/json; charset=utf-8' :
					'application/x-www-form-urlencoded'
			},
			success(res) {
				if (option.blob) { // 要求返回的是二进制文件
					if (res.statusCode == 200) {
						resolve(res.data)
					} else {
						let msg = index !== -1 ? res.data.msg : res.data.Message
						uni.hideLoading()
						uni.showToast({
							title: msg || '服务器异常',
							icon: 'none',
							complete: () => {
								setTimeout(() => {
									reject(res.data)
								}, 1500);
							}
						})
					}
				} else {
					let status = index !== -1 ? res.data.status : res.data.Status
					if (status === 1) {
						resolve({
							data: interceptorResponse(res.data, URL_OBJ.returnType, index),
							pageCount: res.data.Page_Count || 1,
							Status: res.data.Status,
							Message: res.data.Message
						})
					} else {
						let msg = index !== -1 ? res.data.msg : res.data.Message
						uni.hideLoading()
						uni.showToast({
							title: msg || '服务器异常',
							icon: 'none',
							complete: () => {
								setTimeout(() => {
									reject(res.data)
								}, 1500);
							}
						})
					}

				}
			},
			fail(err) {
				if (err && err.errMsg == 'request:fail timeout' || err.errMsg === 'request:fail 请求超时') {
					uni.showToast({
						title: option.timeout || '网络超时,请稍后再试',
						icon: 'none',
						complete: () => {
							setTimeout(() => {
								reject(err)
							}, 1500);
						}
					})
				} else {
					uni.showToast({
						title: typeof(err) == 'string' ? err : '服务器异常',
						icon: 'none',
						complete: () => {
							setTimeout(() => {
								reject(err)
							}, 1500);
						}
					})
				}
			}
		})
	})
}
// 管理系统请求
function adminrequest(url, params = {}, data = {}, method = 'POST', option = {}) {
	let headerMethod = false
	if (data.headerMethod) {
		headerMethod = true
		delete data.headerMethod
	}
	return new Promise((resolve, reject) => {
		const URL_OBJ = HTTP_URL[url]
		baseUrl = store.state.vuex_businessObj.adminRes
		url = baseUrl + URL_OBJ.url
		uni.request({
			url: url + queryParams(params, true),
			method: method,
			data: data,
			timeout: 20000,
			responseType: option.blob ? 'arraybuffer' : 'text',
			header: {
				'content-type': headerMethod ? 'application/json; charset=utf-8' :
					'application/x-www-form-urlencoded'
			},
			success(res) {
				if (option.blob) { // 要求返回的是二进制文件
					if (res.statusCode == 200) {
						resolve(res.data)
					} else {
						let msg = index !== -1 ? res.data.msg : res.data.Message
						uni.hideLoading()
						uni.showToast({
							title: msg || '服务器异常',
							icon: 'none',
							complete: () => {
								setTimeout(() => {
									reject(res.data)
								}, 500);
							}
						})
					}
				} else {
					let status = res.data.Status
					if (status === 1) {
						resolve({
							data: interceptorResponse(res.data, URL_OBJ.returnType, -1),
							pageCount: res.data.Page_Count,
						})
					} else {
						let msg = res.data.Message
						uni.showToast({
							title: msg || '服务器异常',
							icon: 'none',
							complete: () => {
								setTimeout(() => {
									reject(res.data)
								}, 500);
							}
						})
					}

				}
			},
			fail(err) {
				uni.hideLoading()
				uni.showToast({
					title: err || '服务器异常',
					icon: 'none',
					complete: () => {
						setTimeout(() => {
							reject(err)
						}, 1000);
					}
				})
			}
		})
	})
}

function interceptorRequest(url, params) {
	params = {
		business_id: store.state.vuex_business.pk_id || undefined,
		users_id: store.state.vuex_token || undefined,
		// users_id: 1506664,
		...params
	}
	if (!params.business_id) delete params.business_id
	if (!params.users_id) delete params.users_id
	// #ifdef  MP-ALIPAY || MP-TOUTIAO	
	// 支付宝跟字节小程序需要转换一下中文
	return encodeURI(url + queryParams(params, true))
	// #endif 

	// #ifndef  MP-ALIPAY  || MP-TOUTIAO	
	return url + queryParams(params, true)
	// #endif
}

/*
 * index  !== 1:表示是旧版接口
 **/
function interceptorResponse(res, type, index) {
	let result = index !== -1 ? res.data : res.Data
	switch (type) {
		case 'array':
			return result || []
		case 'object':
			return result || {}
		case 'string':
			return result || ''
		case 'arrObj':
			return result && result.length > 0 ? result[0] : {}
	}
}
export function GetQueryDataList(name, page = '1', page_size = '12', params, opts = {}) {
	let url = opts.api ? 'ManageGetQueryDataList' : 'GetQueryDataList'
	if (opts.api) delete opts.api
	opts = {
		sort: '', //排序
		fuzzy_field: opts.setting ? '' : 'name', //模糊查询
		...opts,
	}
	if (opts.setting) delete opts.setting
	params = {
		name,
		page,
		page_size,
		json_where: JSON.stringify(params),
		...opts,
	}
	if (!params.sort) delete params.sort
	return adminrequest(url, params)
}
export function UpdateModifyData(name, param, opts = {}) {
	let sqlParams = JSON.stringify({
		pk_id: param.pk_id
	})
	let url = opts.setting ? 'ManageUpdateModifyData' : 'UpdateModifyData'
	if (opts.setting) delete opts.setting
	if (Object.keys(param).includes('pk_id')) delete param.pk_id
	param = JSON.stringify(param)
	let params = {
		name,
		sign: md5Libs.md5(md5Libs.md5(store.state.vuex_businessObj.adminRes).toUpperCase() + param + sqlParams)
			.toUpperCase(),
		json_where: sqlParams,
		fk_business_id: store.state.vuex_adminuser.optionId,
		account_type: store.state.vuex_adminuser.port_type,
	}
	let data = {
		json: param,
		headerMethod: 'json'
	}
	return adminrequest(url, params, data)
}
/**
 * opt isWeb:是否前端调用 
 */
export function AddNewData(name, param, opt = {}) {
	param = JSON.stringify(param)
	let params = {
		name,
		sign: md5Libs.md5(md5Libs.md5(store.state.vuex_businessObj.adminRes).toUpperCase() + param).toUpperCase(),
		fk_business_id: opt.isWeb ? null : store.state.vuex_adminuser.optionId,
		account_type: opt.isWeb ? null : store.state.vuex_adminuser.port_type,
	}
	let url = 'AddNewData'
	let data = {
		json: param,
		headerMethod: 'json'
	}
	return adminrequest(url, params, data)

}
export function DeleteManagerData(type, pk_id, opts = {}) {
	let url = opts.isBusiness ? 'DeleteData' : 'DeleteManagerData'
	let params = {
		type,
		pk_id,
		sign: md5Libs.md5(md5Libs.md5(store.state.vuex_businessObj.adminRes).toUpperCase() + type).toUpperCase(),
		fk_business_id: store.state.vuex_adminuser.optionId,
		account_type: store.state.vuex_adminuser.port_type,
	}
	return adminrequest(url, params)
}
export function adminPost(url, params, data, key) {
	return adminrequest(url, params, data)
}
/**
 * post请求 默认传参
 * pk_id:商家id
 * user_id:token
 * */
export function resPost(url, params, data, option = {}) {
	return request(url, params, data, 'POST', option)
}
/**
 * get请求 默认传参
 * user_id:token
 * */
export function resGet(url, params, data, option = {}) {
	return request(url, params, data, 'GET', option)
}

export default request
